package extrace.ui.main.ui;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.track.AMapTrackClient;
import com.amap.api.track.ErrorCode;
import com.amap.api.track.OnTrackLifecycleListener;
import com.amap.api.track.TrackParam;
import com.amap.api.track.query.model.AddTerminalRequest;
import com.amap.api.track.query.model.AddTerminalResponse;
import com.amap.api.track.query.model.AddTrackRequest;
import com.amap.api.track.query.model.AddTrackResponse;
import com.amap.api.track.query.model.QueryTerminalRequest;
import com.amap.api.track.query.model.QueryTerminalResponse;

import extrace.ui.main.MainActivity;
import extrace.ui.main.R;
import extrace.ui.main.ui.Constants;
import extrace.ui.main.ui.SimpleOnTrackLifecycleListener;
import extrace.ui.main.ui.SimpleOnTrackListener;


/**
 * 轨迹上报示例
 */
public class TrackService  extends Service{

    private static final String TAG = "TrackServiceActivity";
    private static final String CHANNEL_ID_SERVICE_RUNNING = "CHANNEL_ID_SERVICE_RUNNING";

    private MapView mapView;
    private AMapTrackClient aMapTrackClient;
    private TextView startTrackView;
    private TextView startGatherView;

    private long terminalId;
    private long trackId;
    private boolean isServiceRunning;
    private boolean isGatherRunning;
    private Context context;
    private boolean uploadToTrack = true;
    private Constants constants=new Constants();
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        context=getApplicationContext();

        constants.TERMINAL_NAME =intent.getStringExtra("id");
//        Toast.makeText(context,  constants.TERMINAL_NAME, Toast.LENGTH_SHORT).show();
        aMapTrackClient = new AMapTrackClient(context);
        aMapTrackClient.setInterval(5, 30);
        startTrack();
        updateBtnStatus();

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        aMapTrackClient.stopGather(onTrackListener);
        aMapTrackClient.stopTrack(new TrackParam(Constants.SERVICE_ID, terminalId), onTrackListener);
        super.onDestroy();
    }


    private OnTrackLifecycleListener onTrackListener = new SimpleOnTrackLifecycleListener() {
        @Override
        public void onBindServiceCallback(int status, String msg) {
            Log.w(TAG, "onBindServiceCallback, status: " + status + ", msg: " + msg);
        }

        @Override
        public void onStartTrackCallback(int status, String msg) {
            if (status == ErrorCode.TrackListen.START_TRACK_SUCEE || status == ErrorCode.TrackListen.START_TRACK_SUCEE_NO_NETWORK) {
                // 成功启动
//                Toast.makeText(context, "启动服务成功", Toast.LENGTH_SHORT).show();
                isServiceRunning = true;

                aMapTrackClient.setTrackId(trackId);
                aMapTrackClient.startGather(onTrackListener);

                updateBtnStatus();
            } else if (status == ErrorCode.TrackListen.START_TRACK_ALREADY_STARTED) {
                // 已经启动
//                Toast.makeText(context, "服务已经启动", Toast.LENGTH_SHORT).show();
                isServiceRunning = true;
                updateBtnStatus();
            } else {
                Log.w(TAG, "error onStartTrackCallback, status: " + status + ", msg: " + msg);
                Toast.makeText(context,
                        "error onStartTrackCallback, status: " + status + ", msg: " + msg,
                        Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onStopTrackCallback(int status, String msg) {
            if (status == ErrorCode.TrackListen.STOP_TRACK_SUCCE) {
                // 成功停止
//                Toast.makeText(context, "停止服务成功", Toast.LENGTH_SHORT).show();
                isServiceRunning = false;
                isGatherRunning = false;
                updateBtnStatus();
            } else {
                Log.w(TAG, "error onStopTrackCallback, status: " + status + ", msg: " + msg);
                Toast.makeText(context,
                        "error onStopTrackCallback, status: " + status + ", msg: " + msg,
                        Toast.LENGTH_LONG).show();

            }
        }

        @Override
        public void onStartGatherCallback(int status, String msg) {
            if (status == ErrorCode.TrackListen.START_GATHER_SUCEE) {
//                Toast.makeText(context, "定位采集开启成功", Toast.LENGTH_SHORT).show();
                isGatherRunning = true;
                updateBtnStatus();
            } else if (status == ErrorCode.TrackListen.START_GATHER_ALREADY_STARTED) {
//                Toast.makeText(context, "定位采集已经开启", Toast.LENGTH_SHORT).show();
                isGatherRunning = true;
                updateBtnStatus();
            } else {
                Log.w(TAG, "error onStartGatherCallback, status: " + status + ", msg: " + msg);
                Toast.makeText(context,
                        "error onStartGatherCallback, status: " + status + ", msg: " + msg,
                        Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onStopGatherCallback(int status, String msg) {
            if (status == ErrorCode.TrackListen.STOP_GATHER_SUCCE) {
//                Toast.makeText(context, "定位采集停止成功", Toast.LENGTH_SHORT).show();
                isGatherRunning = false;
                updateBtnStatus();
            } else {
                Log.w(TAG, "error onStopGatherCallback, status: " + status + ", msg: " + msg);
                Toast.makeText(context,
                        "error onStopGatherCallback, status: " + status + ", msg: " + msg,
                        Toast.LENGTH_LONG).show();
            }
        }
    };

//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_track_service);
//        // 不要使用Activity作为Context传入
//     aMapTrackClient    = new AMapTrackClient(getApplicationContext());
//        aMapTrackClient.setInterval(5, 30);
//
//        mapView = findViewById(R.id.activity_track_service_map);
//        mapView.getMap().moveCamera(CameraUpdateFactory.zoomTo(14));
//        mapView.onCreate(savedInstanceState);
//        // 启用地图内置定位
//        mapView.getMap().setMyLocationEnabled(true);
//        mapView.getMap().setMyLocationStyle(
//                new MyLocationStyle()
//                        .interval(2000)
//                        .myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW)
//        );
//
//        startTrackView = findViewById(R.id.activity_track_service_start_track);
//        startGatherView = findViewById(R.id.activity_track_service_start_gather);
//        updateBtnStatus();
//        // 服务启停
//        startTrackView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (isServiceRunning) {
//                    aMapTrackClient.stopTrack(new TrackParam(Constants.SERVICE_ID, terminalId), onTrackListener);
//                } else {
//                    startTrack();
//                }
//            }
//        });
//        // 采集启停
//        startGatherView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (isGatherRunning) {
//                    aMapTrackClient.stopGather(onTrackListener);
//                } else {
//                    aMapTrackClient.setTrackId(trackId);
//                    aMapTrackClient.startGather(onTrackListener);
//                }
//            }
//        });
//
//        ((CheckBox)findViewById(R.id.activity_track_service_upload_to_track)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                uploadToTrack = isChecked;
//            }
//        });
//    }


    private void updateBtnStatus() {
//        Toast.makeText(context,isServiceRunning ? "服务未启动" : "服务启动中",Toast.LENGTH_SHORT).show();
//        Toast.makeText(context,isGatherRunning ? "未采集" : "正在采集",Toast.LENGTH_SHORT).show();
    }

    private void startTrack() {
        // 先根据Terminal名称查询Terminal ID，如果Terminal还不存在，就尝试创建，拿到Terminal ID后，
        // 用Terminal ID开启轨迹服务
        aMapTrackClient.queryTerminal(new QueryTerminalRequest(Constants.SERVICE_ID, constants.TERMINAL_NAME), new SimpleOnTrackListener() {
            @Override
            public void onQueryTerminalCallback(QueryTerminalResponse queryTerminalResponse) {
                if (queryTerminalResponse.isSuccess()) {

                        // 当前终端是新终端，还未创建过，创建该终端并使用新生成的terminal id
                        aMapTrackClient.addTerminal(new AddTerminalRequest(constants.TERMINAL_NAME, constants.SERVICE_ID), new SimpleOnTrackListener() {
                            @Override
                            public void onCreateTerminalCallback(AddTerminalResponse addTerminalResponse) {
                                if (addTerminalResponse.isSuccess()) {
                                    terminalId = addTerminalResponse.getTid();
//                                    TrackParam trackParam = new TrackParam(constants.SERVICE_ID, terminalId);
//                                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                                        trackParam.setNotification(createNotification());
//                                    }
//
//                                    Toast.makeText(context,
//                                            constants.TERMINAL_NAME +"  "+terminalId,
//                                            Toast.LENGTH_LONG).show();
//                                    aMapTrackClient.startTrack(trackParam, onTrackListener);

                                    aMapTrackClient.addTrack(new AddTrackRequest(Constants.SERVICE_ID, terminalId), new SimpleOnTrackListener() {
                                        @Override
                                        public void onAddTrackCallback(AddTrackResponse addTrackResponse) {
                                            if (addTrackResponse.isSuccess()) {
                                                // trackId需要在启动服务后设置才能生效，因此这里不设置，而是在startGather之前设置了track id
                                                constants.trid=addTrackResponse.getTrid();
                                                trackId = constants.trid;
//                                                Toast.makeText(context,
//                                                        addTrackResponse.getTrid() +"  "+terminalId+' '+constants.TERMINAL_NAME,
//                                                        Toast.LENGTH_LONG).show();

                                                TrackParam trackParam = new TrackParam(constants.SERVICE_ID, terminalId);
                                                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                                    trackParam.setNotification(createNotification());
                                                }
//                                        trackParam.setTrackId(trackId);
                                                aMapTrackClient.startTrack(trackParam, onTrackListener);
                                            } else {
                                                Toast.makeText(context, "网络请求失败，" + addTrackResponse.getErrorMsg(), Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                                } else {
                                    Toast.makeText(context, "网络请求失败，" + addTerminalResponse.getErrorMsg(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }

            }
        });
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private Notification createNotification() {
        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID_SERVICE_RUNNING, "app service", NotificationManager.IMPORTANCE_LOW);
            nm.createNotificationChannel(channel);
            builder = new Notification.Builder(getApplicationContext(), CHANNEL_ID_SERVICE_RUNNING);
        } else {
            builder = new Notification.Builder(getApplicationContext());
        }
        Intent nfIntent = new Intent(this, MainActivity.class);
        nfIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("猎鹰sdk运行中")
                .setContentText("猎鹰sdk运行中");
        Notification notification = builder.build();
        return notification;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
